﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Messages
{

    public partial class MessagesBoard : System.Web.UI.Page
    {
        //数据连接最基本需要的两个对象
        private SqlConnection conn = null;
        private SqlCommand cmd = null;
        //private SqlDataAdapter adapter = null;
        //为了方便，设为全局对象的sql语句
        private string sql = null;

        //公用 打开数据库的方法
        public void OpenDatabase()
        {
            conn = new SqlConnection
            {
                //catalog自己的数据库
                ConnectionString = "Integrated Security=SSPI;Data Source=(local);initial catalog=MessagesBoard;User ID =sa;password=123456"
            };
            if (conn.State == ConnectionState.Closed)
            {
               
                conn.Open();
                
                //Response.Write("<script>alert('Connected!');</script>");
            }
        }

        //封装的数据库语句执行的方法  
        public void Execute(String sql)
        {
            OpenDatabase();
            cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();//执行的方法里已经有了关闭数据库的操作

        }

        //加载数据
        private new void Load()
        {

            OpenDatabase();

            DataTable dt = new DataTable();

            cmd = new SqlCommand("select * from messages order by M_id desc", conn);

            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            adapter.Fill(dt);

            RepeaterMessages.DataSource = dt;
            RepeaterMessages.DataBind();

            //throw new NotImplementedException();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Load();

                

            }
           
        }

        protected bool ComfirmUser()
        {
            Boolean flag = false;//假设用户不存在
            if (Request["userAccount"] != null)
            {

                string userAccount = Request.Form["userAccount"];
                string userPW = Request.Form["userPW"];
                //string userAccount = Request["userAccount"].ToString();
                //string userPW = Request["userPW"].ToString();

            }

            




            return flag;
        }


        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {

            sql = "insert into messages(M_userName,M_message,M_date) values('" + TextBoxAuthor.Text.ToString().Trim() + "','" + TextBoxMessage.Text.ToString().Trim() + "','"+ DateTime.Now.ToLocalTime().ToString() + "')";

            Execute(sql);

            Load();

        }

        
    }
}